from modules import member
from common import MemberEntity, utility
from dataaccess import MemberData
from businessrules import MemberBiz
import hashlib

def profile():
    memberdata = MemberData.MemberData().SelectMemberByID(session.username)
    if(request.env.request_method == "POST"):
        memberdata.Name = request.vars.get("name") 
        memberdata.Email = request.vars.get("email") 
        memberdata.Gender = request.vars.get("gender") 
        memberdata.Address = request.vars.get("address") 
        memberdata.BirthDate = request.vars.get("birthdate") 
        memberdata.Phone = request.vars.get("phone") 
        MemberBiz.MemberBiz().UpdateMember(memberdata)
    print(memberdata.Name)
    return dict(memberdata=memberdata)

def apply():
    return dict()

def login():
  if request.env.request_method == "POST" :
    salt = b"Ha71bcea5NtV9247c4a331Dyf5"
    email = request.vars.get('email')  
    password = request.vars.get('password', "")  
    name = request.vars.get('name')  
    member = MemberData.MemberData().SelectMemberByID(email)
    hash = hashlib.md5(salt+password).hexdigest()

    print(email)
    print(member)
    if member and member.Password == hash:
      session.username = member.Email
      print("session username:" + session.username)
      session.usertype = member.UserType
      redirect(URL('member','profile'))
    else:
      redirect(URL('member','register'))
  else:
      redirect(URL('member','register'))

def register():
  salt = b"Ha71bcea5NtV9247c4a331Dyf5"
  if request.env.request_method == "POST" :
    email = request.vars.get('email')  
    name = request.vars.get('name', "")  
    raw_password = request.vars.get('password', "")  
    password = hashlib.md5(salt+raw_password).hexdigest()
    userType = utility.UserType.Member
    member = MemberEntity.MemberEntity(username=email, name=name, email=email,userType=userType,password=password)
    MemberData.MemberData().InsertMember(member)
    session.username = email
    session.usertype = userType
    redirect(URL('member','profile'))
  else:
    return dict()

def logout():
    session.username = None
    session.usertype = None
    redirect(URL('default','index'))

